//
//  ImageManager.m
//  UseData
//
//  Created by Lenny on 16/5/17.
//  Copyright © 2016年 Lenny. All rights reserved.
//

#import "ImageManager.h"

#import <CommonCrypto/CommonDigest.h>

@implementation ImageManager

+ (instancetype)shareManager {
    
    static ImageManager *intance = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        
        intance = [[ImageManager alloc] init];
    });
    return intance;
}

- (NSString *)findFilePath{
    
    NSString *pathCach = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *fileName = @"Lenny";
    NSString *fullPath = [NSString stringWithFormat:@"%@/%@",pathCach,fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL existed = [fileManager fileExistsAtPath:fullPath];
    if (existed == NO) {
        //没有就新建文件
        [fileManager createDirectoryAtPath:fullPath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    return fullPath;
}

- (NSString *)getNameWithStr:(NSString *)fileName {
    
    const char *str = [fileName UTF8String];
    NSString *fileNameType = [fileName pathExtension];
    NSMutableString *fileNameMd5 = [NSMutableString string];
    //设置为md5
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    for (int i = 0; i < CC_MD5_DIGEST_LENGTH; i ++) {
        [fileNameMd5 appendFormat:@"%02x",r[i]];
    }
    //添加扩展名
    if (![fileNameType isEqual:@""]) {
        [fileNameMd5 appendFormat:@".%@",fileNameType];
    }
    return fileNameMd5;
}

- (BOOL)isCheck:(NSString *)name {
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [self findFilePath];
    NSArray *nameList = [[NSArray alloc] initWithArray:[fileManager contentsOfDirectoryAtPath:path error:nil]];
    return [nameList containsObject:name];
}

- (void)saveWithImage:(UIImage *)image withName:(NSString *)fileName {
    
    //图片名字
    NSString *name = [self getNameWithStr:fileName];
    //获取全路径
    NSString *path = [self findFilePath];
    NSString *fullPath = [NSString stringWithFormat:@"%@%@",name,path];
    NSData *imageData = UIImagePNGRepresentation(image);
    [imageData writeToFile:fullPath options:NSAtomicWrite error:nil];
}

@end
